<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElButton, ElImage, ElTabs, ElTabPane, ElRate, ElMessage, ElSelect, ElOption, ElInputNumber } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { productByIdService,getRelatedProductService } from '@/api/product.js'

const route = useRoute()
const router = useRouter()
const productId = ref(route.params.id)
const cartStore = useCartStore()
const isLoading = ref(false)

// 监听路由参数变化
watch(() => route.params.id, async (newId) => {
  isLoading.value = true
  productId.value = newId
  try {
    await getProductById()
    await getRelatedProducts()
    // 滚动到页面顶部
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  } catch (error) {
    console.error('切换商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  } finally {
    // 确保无论成功或失败，加载状态都会解除
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
})

// 商品规格选择
const selectedSpecs = ref({})
const quantity = ref(1)



// 相关推荐商品
const relatedProducts = ref([])
const getRelatedProducts = async () => {
  try {
    let result = await getRelatedProductService(productId.value)
    if (result.data && Array.isArray(result.data)) {
      // 随机排序并取前4个
      const shuffled = result.data.sort(() => 0.5 - Math.random());
      relatedProducts.value = shuffled.slice(0, 4);
      console.log('相关推荐商品:', relatedProducts.value)
    } else {
      relatedProducts.value = []
      console.log('没有相关推荐商品')
    }
  } catch (error) {
    ElMessage.error('获取相关推荐商品失败')
    console.error('获取相关推荐商品失败:', error)
  }
}


const product = ref(null)
const currentMainImage = ref('')

const getProductById = async () => { 
  let result = await productByIdService(productId.value)
  product.value = result.data
  console.log('Fetched product data:', product.value)

  // 如果photoWall存在，将主图添加到photoWall的开头
  if (product.value.photoWall) {
    product.value.photoWall.unshift(product.value.image)
  } else {
    // 如果photoWall不存在，则创建一个包含主图的photoWall
    product.value.photoWall = [product.value.image]
  }
  currentMainImage.value = product.value.image // 初始化主图

  // 初始化规格选择
  if (product.value && product.value.specs) {
    const filteredSpecs = {};
    Object.keys(product.value.specs).forEach(key => {
      const value = product.value.specs[key];
      // 只保留非null且非空字符串的规格
      if (value !== null && value !== '') {
        // 如果值是字符串，转换为数组
        if (typeof value === 'string') {
          filteredSpecs[key] = [value];
        } else if (Array.isArray(value)) {
          // 如果是数组，确保不是空数组
          if (value.length > 0) {
            filteredSpecs[key] = value;
          }
        } else {
          // 对于其他非空类型，直接保留
          filteredSpecs[key] = [value]; // Ensure it's an array for consistency
        }
      }
    });
    product.value.specs = filteredSpecs;

    // 初始化selectedSpecs
    Object.keys(product.value.specs).forEach(key => {
      const options = product.value.specs[key];
      if (options && options.length > 0) {
        selectedSpecs.value[key] = options[0];
      }
    });
  }
}
// 模拟用户评价数据
const reviews = ref([
  {
    id: 1,
    username: '张三',
    rating: 5,
    comment: '手机非常好用，性能强劲，拍照清晰！',
    date: '2024-05-20',
    images: ['https://picsum.photos/200/200?random=1', 'https://picsum.photos/200/200?random=2'],
    likes: 128,
    isVerified: true
  },
  {
    id: 2,
    username: '李四',
    rating: 4,
    comment: 'MacBook Air M2 续航给力，轻便易携带，办公学习非常方便。',
    date: '2024-05-18',
    images: ['https://picsum.photos/200/200?random=3'],
    likes: 56,
    isVerified: true
  },
  {
    id: 3,
    username: '王五',
    rating: 5,
    comment: 'Nike Air Force 1 经典百搭，穿起来很舒服，非常满意！',
    date: '2024-05-15',
    images: [],
    likes: 89,
    isVerified: false
  }
])

onMounted(async () => {
  isLoading.value = true 
  try {
    await getProductById()
    await getRelatedProducts()
  } catch (error) {
    ElMessage.error('获取商品详情失败')
    console.error('获取商品详情失败:', error)
  } finally {
    // 确保无论成功或失败，加载状态都会解除
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
})

const handleAddToCart = async () => {
  if (!product.value) {
    ElMessage.error('商品信息不存在')
    return
  }

  // 验证数量
  if (quantity.value < 1) {
    ElMessage.error('请选择有效的商品数量')
    return
  }

  // 验证库存
  if (quantity.value > product.value.stock) {
    ElMessage.error('商品库存不足')
    return
  }

  try {
    // 调试：显示规格信息
    console.log('📦 [商品详情] 商品规格:', product.value.specs)
    console.log('📦 [商品详情] 选中的规格:', selectedSpecs.value)
    console.log('📦 [商品详情] 商品规格类型:', typeof product.value.specs)
    console.log('📦 [商品详情] 商品规格是否为对象:', product.value.specs && typeof product.value.specs === 'object')
    
    // 验证specs格式
    if (product.value.specs) {
      Object.keys(product.value.specs).forEach(key => {
        console.log(`📦 [商品详情] 规格 ${key}:`, product.value.specs[key], '类型:', typeof product.value.specs[key], '是否为数组:', Array.isArray(product.value.specs[key]))
      })
    }
    
    const cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      originalPrice: product.value.originalPrice,
      image: product.value.image,
      stock: product.value.stock,
      selectedSpecs: { ...selectedSpecs.value }, // 只传递选中的规格值
      quantity: quantity.value
    }
    
    // 调试：显示构建的购物车项数据
    console.log('📦 [商品详情] 构建的cartItem:', cartItem)
    console.log('📦 [商品详情] cartItem.selectedSpecs:', cartItem.selectedSpecs)
    
    // 显示加载状态
    const loading = ElMessage({
      message: '正在添加到购物车...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    await cartStore.addToCart(cartItem)
    
    // 关闭加载消息
    loading.close()
    
    // 重置数量为1
    quantity.value = 1
    
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败，请重试')
  }
}

const handleBuyNow = async () => {
  if (!product.value) {
    ElMessage.error('商品信息不存在')
    return
  }

  // 验证数量
  if (quantity.value < 1) {
    ElMessage.error('请选择有效的商品数量')
    return
  }

  // 验证库存
  if (quantity.value > product.value.stock) {
    ElMessage.error('商品库存不足')
    return
  }

  try {
    const cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      originalPrice: product.value.originalPrice,
      image: product.value.image,
      stock: product.value.stock,
      selectedSpecs: { ...selectedSpecs.value }, // 只传递选中的规格值
      quantity: quantity.value
    }
    
    // 先添加到购物车
    await cartStore.addToCart(cartItem)
    
    // 跳转到购物车页面
    router.push('/home/cart')
    
  } catch (error) {
    console.error('立即购买失败:', error)
    ElMessage.error('立即购买失败，请重试')
  }
}

const handleShare = () => {
  // 实现分享功能
  ElMessage.success('分享链接已复制到剪贴板')
}

const handleQuantityChange = (value) => {
  quantity.value = value
}

const handleThumbnailClick = (image) => {
  currentMainImage.value = image
}

const handleRelatedProductClick = (productId) => {
  router.push(`/home/product/${productId}`)
}
</script>

<template>
  <CommonHeader />
  <FloatingSidebar />

  <div class="product-detail">
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
    </div>
    <div class="container" v-if="product" :class="{ 'fade-enter': !isLoading }">
      <!-- 商品基本信息 -->
      <div class="product-info">
        <div class="product-gallery">
          <el-image 
            :src="currentMainImage" 
            fit="cover"
            class="main-image"
          />
          <div class="thumbnail-list" v-if="product.photoWall && product.photoWall.length > 0">
            <el-image 
              v-for="(image, index) in product.photoWall" 
              :key="index"
              :src="image"
              fit="cover"
              class="thumbnail"
              @click="handleThumbnailClick(image)"
              :class="{ active: image === currentMainImage }"
            />
          </div>
        </div>
        <div class="product-details-content">
          <h1 class="product-title">{{ product.name }}</h1>
          <div class="price-section">
            <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
            <span v-if="product.originalPrice && product.originalPrice > product.price" class="original-price">¥{{ product.originalPrice.toFixed(2) }}</span>
          </div>
          <div class="sales-stock">
            <span class="sales-info">月销：{{ product.sold }}</span>
            <span class="stock-info">库存：{{ product.stock }}</span>
            <span class="comment-info">评价：{{ product.commentCount }}</span>
          </div>
          
          
          <!-- 规格选择 -->
          <div class="specs-selection" v-if="product.specs && Object.keys(product.specs).length > 0">
            <div v-for="(options, specName) in product.specs" :key="specName" class="spec-group">
              <div class="spec-label">{{ specName }}：</div>
              <div class="spec-options">
                <el-select v-model="selectedSpecs[specName]" class="spec-select">
                  <el-option
                    v-for="option in (Array.isArray(options) ? options : [options])"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </div>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-selection">
            <span class="quantity-label">数量：</span>
            <el-input-number 
              v-model="quantity" 
              :min="1" 
              :max="product.stock"
              @change="handleQuantityChange"
            />
          </div>

          <!-- 服务承诺 -->
          <div class="services-section">
            <div v-for="(service, index) in product.services.split('\n')" :key="index" class="service-item">
              <i class="el-icon-check"></i>
              <span>{{ service.replace(/'/g, '') }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" size="large" @click="handleAddToCart" class="add-to-cart-button">
              加入购物车
            </el-button>
            <el-button type="danger" size="large" @click="handleBuyNow" class="buy-now-button">
              立即购买
            </el-button>
            <el-button type="info" size="large" @click="handleShare" class="share-button">
              分享
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品详情和评价 -->
      <div class="product-tabs">
        <el-tabs type="border-card">
          <el-tab-pane label="商品详情">
            <div class="product-description">
              <p class="description-text">{{ product.description }}</p>
              <div v-for="(section, index) in product.details" :key="index" class="detail-section">
                <h3>{{ section.title }}</h3>
                <ul>
                  <li v-for="(item, idx) in section.content" :key="idx">{{ item }}</li>
                </ul>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="用户评价 ">
            <div class="reviews-section">
              <div class="review-item" v-for="review in reviews" :key="review.id">
                <div class="review-header">
                  <span class="username">{{ review.username }}</span>
                  <span v-if="review.isVerified" class="verified-badge">已购</span>
                  <el-rate v-model="review.rating" disabled show-score text-color="#ff9900" score-template="{value}"></el-rate>
                </div>
                <p class="review-comment">{{ review.comment }}</p>
                <div class="review-images" v-if="review.images.length > 0">
                  <el-image 
                    v-for="(image, idx) in review.images" 
                    :key="idx"
                    :src="image"
                    class="review-image"
                  />
                </div>
                <div class="review-footer">
                  <span class="review-date">{{ review.date }}</span>
                  <div class="review-actions">
                    <span class="like-button">
                      <i class="el-icon-thumb"></i>
                      {{ review.likes }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 相关推荐 -->
      <div class="related-products">
        <h2 class="section-title">相关推荐</h2>
        <div class="related-products-grid">
          <div v-for="item in relatedProducts" :key="item.id" class="related-product-card" @click="handleRelatedProductClick(item.id)">
            <el-image :src="item.image" class="related-product-image" />
            <div class="related-product-info">
              <h3>{{ item.name }}</h3>
              <div class="related-product-price">¥{{ item.price.toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-empty v-else description="商品未找到或正在加载..." style="min-height: calc(100vh - 120px);"></el-empty>
  </div>
  
  <CommonFooter />
</template>

<style scoped>
.product-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.product-info {
  display: flex;
  gap: 40px;
  margin-bottom: 30px;
}

.product-gallery {
  flex-shrink: 0;
  width: 450px;
}

.main-image {
  width: 100%;
  height: 450px;
  object-fit: contain;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 15px;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.thumbnail.active,
.thumbnail:hover {
  border-color: #409EFF;
}

.product-details-content {
  flex-grow: 1;
}

.product-title {
  font-size: 28px;
  color: #303133;
  margin-top: 0;
  margin-bottom: 20px;
  font-weight: bold;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 25px;
  padding: 15px 0;
  border-top: 1px dashed #ebeef5;
  border-bottom: 1px dashed #ebeef5;
}

.current-price {
  font-size: 38px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 15px;
}

.original-price {
  font-size: 20px;
  color: #909399;
  text-decoration: line-through;
}

.sales-stock {
  font-size: 15px;
  color: #909399;
  margin-bottom: 25px;
  display: flex;
  gap: 25px;
}

.sales-info,
.stock-info,
.comment-info {
  padding: 0 10px;
  border-right: 1px solid #ebeef5;
}

.comment-info {
  border-right: none;
}

.specs-selection {
  margin-bottom: 25px;
}

.spec-group {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

.spec-label {
  width: 90px;
  color: #606266;
  font-weight: bold;
  font-size: 15px;
}

.spec-select {
  width: 220px;
}

.spec-select :deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  border-radius: 6px;
}

.quantity-selection {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
}

.quantity-label {
  width: 90px;
  color: #606266;
  font-weight: bold;
  font-size: 15px;
}

.services-section {
  margin: 25px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.service-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #606266;
  font-size: 15px;
}

.service-item i {
  color: #67c23a;
  margin-right: 10px;
  font-size: 18px;
}

.action-buttons {
  display: flex;
  gap: 20px;
  margin-top: 35px;
}

.add-to-cart-button,
.buy-now-button,
.share-button {
  flex: 1;
  max-width: 220px;
  padding: 14px 0;
  font-size: 16px;
  border-radius: 8px;
}

.buy-now-button {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
.buy-now-button:hover {
  background-color: #ebb549; 
  border-color: #ebb549;
}

.product-tabs {
  margin-top: 40px;
}

.product-description {
  line-height: 1.9;
  color: #606266;
  font-size: 15px;
}

.detail-section {
  margin-bottom: 40px;
}

.detail-section h3 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: bold;
}

.detail-section ul {
  list-style: none;
  padding: 0;
}

.detail-section li {
  margin-bottom: 10px;
  padding-left: 25px;
  position: relative;
  font-size: 15px;
  color: #606266;
}

.detail-section li::before {
  content: "•";
  position: absolute;
  left: 0;
  color: #409EFF;
  font-size: 1.2em;
  top: 0;
}

.reviews-section {
  padding: 20px 0;
}

.review-item {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.review-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: bold;
  color: #303133;
  margin-right: 15px;
  font-size: 16px;
}

.verified-badge {
  background-color: #67c23a;
  color: white;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 13px;
  margin-right: 15px;
}

.review-comment {
  color: #606266;
  line-height: 1.7;
  margin: 8px 0;
  font-size: 15px;
}

.review-images {
  display: flex;
  gap: 12px;
  margin: 12px 0;
  flex-wrap: wrap;
}

.review-image {
  width: 110px;
  height: 110px;
  object-fit: cover;
  border-radius: 6px;
}

.review-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.review-date {
  font-size: 13px;
  color: #909399;
}

.review-actions {
  display: flex;
  gap: 20px;
}

.like-button {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  cursor: pointer;
  font-size: 15px;
  transition: color 0.2s ease;
}

.like-button:hover {
  color: #409EFF;
}

.related-products {
  margin-top: 50px;
  padding-top: 30px;
  border-top: 1px solid #ebeef5;
}

.section-title {
  font-size: 26px;
  color: #303133;
  margin-bottom: 25px;
  text-align: center;
  font-weight: bold;
}

.related-products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 25px;
}

.related-product-card {
  border: 1px solid #ebeef5;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.related-product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.related-product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-bottom: 1px solid #ebeef5;
}

.related-product-info {
  padding: 15px;
  text-align: center;
}

.related-product-info h3 {
  font-size: 17px;
  color: #303133;
  margin: 0 0 10px 0;
  font-weight: normal;
}

.related-product-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.no-reviews {
  text-align: center;
  color: #909399;
  padding: 30px 0;
  font-size: 16px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409EFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.fade-enter-active {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media screen and (max-width: 1024px) {
  .product-info {
    flex-direction: column;
    gap: 30px;
  }

  .product-gallery {
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
  }

  .main-image {
    height: 350px;
  }

  .product-details-content {
    padding: 0 10px;
  }

  .product-title {
    font-size: 24px;
  }

  .current-price {
    font-size: 32px;
  }

  .original-price {
    font-size: 18px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }

  .add-to-cart-button,
  .buy-now-button,
  .share-button {
    max-width: none;
    width: 100%;
  }

  .related-products-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }

  .related-product-image {
    height: 160px;
  }
}

@media screen and (max-width: 768px) {
  .container {
    padding: 20px;
  }

  .product-title {
    font-size: 20px;
  }

  .current-price {
    font-size: 28px;
  }

  .original-price {
    font-size: 16px;
  }

  .sales-stock {
    flex-direction: column;
    gap: 10px;
  }

  .sales-info,
  .stock-info,
  .comment-info {
    border-right: none;
    padding: 0;
  }

  .spec-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .spec-label {
    width: auto;
  }

  .spec-select {
    width: 100%;
  }

  .quantity-selection {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .quantity-label {
    width: auto;
  }

  .related-products-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
  }

  .related-product-image {
    height: 140px;
  }
}
</style> 